/* global window */
import axios from 'axios'
import qs from 'qs'
import jsonp from 'jsonp'
import lodash from 'lodash'
import pathToRegexp from 'path-to-regexp'
import { message } from 'antd'
import { YQL, CORS, host } from './config'

const fetch = (options) => {
  let {
    method = 'get',
    data,
    fetchType,
    url,
  } = options
  if (data == undefined) {
    data = {}
  }
  data.token = sessionStorage.getItem('token')
  const cloneData = lodash.cloneDeep(data)

  try {
    let domin = ''
    if (url.match(/[a-zA-z]+:\/\/[^/]*/)) {
      domin = url.match(/[a-zA-z]+:\/\/[^/]*/)[0]
      url = url.slice(domin.length)
    }
    const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    for (let item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domin + url
  } catch (e) {
    message.error(e.message)
  }

  if (fetchType === 'JSONP') {
    return new Promise((resolve, reject) => {
      jsonp(url, {
        param: `${qs.stringify(data)}&callback`,
        name: `jsonp_${new Date().getTime()}`,
        timeout: 4000,
      }, (error, result) => {
        if (error) {
          reject(error)
        }
        resolve({ statusText: 'OK', status: 200, data: result })
      })
    })
  } else if (fetchType === 'YQL') {
    url = `http://query.yahooapis.com/v1/public/yql?q=select * from json where url='${options.url}?${encodeURIComponent(qs.stringify(options.data))}'&format=json`
    data = null
  }

  const config = {
    method: options.method,
    url: options.url,
    baseURL: host,
    timeout: 5000,
    // withCredentials:true
  }
  if (options.method.toLowerCase() === 'get') {
    config.params = cloneData
  } else {
    let str = ''
    for (let key in cloneData) {
      const obj = cloneData[key]
      if (obj instanceof Array) {
        // 如果是数组，需要单独处理
        for (let item of obj) {
          str += `&${key}=${item}`
        }
      } else {
        str += `&${key}=${obj}`
      }
    }
    str = str.substr(1)
    config.data = str
  }
  return axios(config)
  /*
  switch (method.toLowerCase()) {
    case 'get':
      return axios.get(url, {
        params: qs.stringify(cloneData),
        withCredentials:true
      })
    case 'delete':
      return axios.delete(url, {
        data: qs.stringify(cloneData),
      })
    case 'post':
      return axios.post(url, {
        data:cloneData,
        withCredentials:true
      })
    case 'put':
      return axios.put(url, qs.stringify(cloneData))
    case 'patch':
      return axios.patch(url, qs.stringify(cloneData))
    default:
      return axios(options)
  } */
}

export default function request (options) {
  if (options.url && options.url.indexOf('//') > -1) {
    const origin = `${options.url.split('//')[0]}//${options.url.split('//')[1].split('/')[0]}`
    if (window.location.origin !== origin) {
      if (CORS && CORS.indexOf(origin) > -1) {
        options.fetchType = 'CORS'
      } else if (YQL && YQL.indexOf(origin) > -1) {
        options.fetchType = 'YQL'
      } else {
        options.fetchType = 'JSONP'
      }
    }
  }

  return fetch(options).then((response) => {
    const { statusText, status } = response

    let data = options.fetchType === 'YQL' ? response.data.query.results.json : response.data
    if (data.code && data.code != 0) {
      const error = new Error(JSON.stringify(data))

      error.response = {
        data: {
          code: data.code,
          message: data.msg,
        },
      }

      throw error
    }
    if (data instanceof Array) {
      data = {
        list: data,
      }
    }

    return {
      success: true,
      message: statusText,
      statusCode: status,
      ...data,
    }
  }).catch((error) => {
    const { response } = error
    let msg
    let statusCode
    if (response && response instanceof Object) {
      const { data, statusText } = response
      statusCode = response.status||data.code
      msg = data.message || statusText
    } else {
      statusCode = 600
      msg = error.message || 'Network Error'
    }
    
    throw new Error(JSON.stringify({code:statusCode,msg}))
  })
}
